package com.tobby.camelinaction.pools;

import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.apache.camel.Endpoint;
import org.apache.camel.impl.DefaultComponent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MyComponent extends DefaultComponent implements Runnable {

	private static final Logger logger = LoggerFactory.getLogger(MyComponent.class);

	private ScheduledExecutorService executor;

	@Override
	public void run() {
		// this is the task been executed every second
		logger.info("I run now");
	}

	@Override
	protected Endpoint createEndpoint(String uri, String remaining,
			Map<String, Object> parameters) throws Exception {
		return null;
	}

	@Override
	protected void doStart() throws Exception {
		super.doStart();
		// create a scheduled thread pool with 1 thread as we only need one task as
		// background task
		executor = getCamelContext().getExecutorServiceManager()
				.newScheduledThreadPool(this, "MyBackGroundTask", 1);
		// schedule the task to run once every second
		executor.scheduleWithFixedDelay(this, 1, 2, TimeUnit.SECONDS);
	}

	@Override
	protected void doStop() throws Exception {
		// shutdown the thread pool
		getCamelContext().getExecutorServiceManager().shutdown(executor);
		super.doStop();
	}

}
